'use strict'

class WebsocketClient {

    constructor() {
        this.ws = null
        this.connected = false
        this.connectRetryCount = 0
        this.callBackMapping = {}
    }

    connect(url) {
        if (this.ws) return
        if (!window.WebSocket) // 连接服务器
            throw '您的浏览器不支持WebSocket'
        this.ws = new WebSocket(url)
        this.ws.onopen = () => { // 连接成功
            this.connected = true
            // 执行回调
            this.callBackMapping['onopen'] && this.callBackMapping['onopen']()
        }
        this.ws.onclose = (e) => { // 连接关闭
            console.log(e)
            this.ws = null
            this.connectRetryCount++
            if (this.connectRetryCount <= 4) { // 默认重连4次
                return setTimeout(() => {
                    this.connect(url)
                }, this.connectRetryCount * 1000) // 每次重连时间递增
            }
            this.connected = false
            // 执行回调
            this.callBackMapping['onclose'] && this.callBackMapping['onclose']()
        }
        this.ws.onmessage = ev => { // 获得服务端信息
            // 执行回调
            this.connectRetryCount = 0
            this.callBackMapping['onmessage'] && this.callBackMapping['onmessage'](ev)
        }
        this.ws.onerror = e => { // 连接异常
            // 执行回调
            this.callBackMapping['onerror'] && this.callBackMapping['onerror'](e)
        }
    }

    close() {
        if (this.connected && this.ws)
            this.ws.close()
    }

    send(data) {
        // 判断此时此刻有没有连接成功
        if (this.connected && this.connectRetryCount === 0) {
            this.ws.send(data)
        }
    }

    // 注册回调函数
    registerCallBack(socketType, callBack) {
        this.callBackMapping[socketType] = callBack
    }

    // 注销回调函数
    cancelCallBack(socketType) {
        this.callBackMapping[socketType] = null
    }
}

export default WebsocketClient